import { DeleteOutlined, EditOutlined } from '@ant-design/icons'
import { Button } from 'antd'
import { connect } from 'dva'
import { nanoid } from 'nanoid'
import { useState } from 'react'

import { deleteOrgApi, queryOrgTreeApi, resetUserPasswordApi, saveOrUpdateApi } from '@/api/sys/organization'
import AekButton from '@/components/AekButton'
import AekLinkButton from '@/components/AekLinkButton'
import AekTable from '@/components/AekTable'
import AekTree from '@/components/AekTree'
import Ellipsis from '@/components/Ellipsis'
import PageLayout from '@/components/PageLayout'
import SearchForm from '@/components/SearchForm'
import { namespace } from '@/models/sys/organization'
import { getPagination, getRowSelection, message, modal } from '@/utils/antdHelper'
import { getBasicFn } from '@/utils/dvaUtil/index'
import { requestWithTry } from '@/utils/request'

import BatchEditModal from './components/BatchEditModal'
import EditDeptModal from './components/EditDeptModal'
import EditModal from './components/EditModal'
import styles from './index.module.less'

/** 系统 - 部门管理 */
const Index = ({ modelState, loading }) => {
  const { pageList, pagination, searchParams } = modelState
  const { toAction, getLoading } = getBasicFn({ namespace, loading })
  const [selectedRow, setSelectedRow] = useState([])

  const [reloadKey, setReloadKey] = useState(nanoid())

  const addDept = async () => {
    await EditDeptModal.PromiseThen()
    message.success('新增成功')
    setReloadKey(nanoid())
  }

  const editDept = async row => {
    await EditDeptModal.PromiseThen({
      row,
    })
    message.success('修改成功')
    setReloadKey(nanoid())
  }

  const deleteDept = async ({ departmentId, departmentName }) => {
    modal.confirm({
      title: `确认删除部门【${departmentName}】？`,
      onOk: async () => {
        await requestWithTry(deleteOrgApi, { departmentId })
        message.success('删除成功')
        setReloadKey(nanoid())
      },
    })
  }

  const add = async () => {
    await EditModal.PromiseThen()
    message.success('新增成功')
    toAction('getPageList')
  }

  const edit = async row => {
    await EditModal.PromiseThen({ row })
    message.success('修改成功')
    toAction('getPageList')
  }

  const batchEdit = async () => {
    await BatchEditModal.PromiseThen({ selectedRow })
    message.success('修改成功')
    toAction('getPageList')
  }

  const reset = async ({ userId, fullName }) => {
    modal.confirm({
      title: `确认重置【${fullName}】的密码？（重置后，默认密码：YB123456）`,
      onOk: async () => {
        await requestWithTry(resetUserPasswordApi, { userId })
        message.success('重置密码成功')
        toAction('getPageList')
      },
    })
  }

  const remove = async ({ id, fullName }) => {
    modal.confirm({
      title: `确认注销【${fullName}】？`,
      onOk: async () => {
        await requestWithTry(saveOrUpdateApi, { id, delete: true })
        message.success('注销成功')
        if ((pagination.current - 1) * pagination.pageSize === pagination.total - 1) {
          toAction('getPageList', { current: pagination.current - 1 || 1 })
        } else {
          toAction('getPageList')
        }
      },
    })
  }

  const enable = async ({ id }) => {
    await requestWithTry(saveOrUpdateApi, { id, disabled: false })
    message.success('启用成功')
    toAction('getPageList')
  }

  const disable = async ({ id, fullName }) => {
    modal.confirm({
      title: `确认禁用【${fullName}】？`,
      onOk: async () => {
        await requestWithTry(saveOrUpdateApi, { id, disabled: true })
        message.success('禁用成功')
        toAction('getPageList')
      },
    })
  }

  /** @type {import("@/components/AekTree").AekTreeProps} */
  const treeProps = {
    api: queryOrgTreeApi,
    fieldNames: {
      key: 'departmentId',
      title: 'departmentName',
    },
    onSelect: selectedKeys => {
      toAction({
        searchParams: { departmentId: selectedKeys[0] },
        pagination: { ...pagination, current: 1 },
      })
      toAction('getPageList')
    },
    titleRender: item => (
      <div className={`flex ${styles.dept}`}>
        <Ellipsis>{item.departmentName}</Ellipsis>
        <div
          className={`ml20px flex-none ${styles.opera}`}
          onClick={e => {
            e.stopPropagation?.()
          }}
        >
          <EditOutlined className='c-primary' type='edit' onClick={() => editDept(item)} />
          <DeleteOutlined
            className='ml10px c-del'
            type='delete'
            onClick={() => {
              deleteDept(item)
            }}
          />
        </div>
      </div>
    ),
  }

  /** @type {import("@/components/SearchForm").SearchFormProps} */
  const searchProps = {
    searchParams,
    formData: [
      {
        field: 'fullName',
        label: '姓名',
        component: {
          name: 'Input',
        },
      },
      {
        field: 'userName',
        label: '用户名',
        component: {
          name: 'Input',
        },
      },
      {
        field: 'mobileNumber',
        label: '联系方式',
        component: {
          name: 'Input',
        },
      },
      {
        field: 'jobNumber',
        label: '工号',
        component: {
          name: 'Input',
        },
      },
    ],
    onSearch: values => {
      toAction({ searchParams: values })
      toAction({ pagination: { current: 1 } }, true)
      toAction('getPageList')
    },
  }

  /** @type {import("@/components/AekTable").AekTableProps} */
  const tableProps = {
    configKey: namespace,
    rowKey: 'id',
    loading: getLoading('getPageList'),
    dataSource: pageList,
    pagination: getPagination(pagination, (current, pageSize) => {
      toAction('getPageList', { current, pageSize })
    }),
    columns: [
      { dataIndex: 'fullName', title: '姓名' },
      { dataIndex: 'userName', title: '用户名' },
      { dataIndex: 'mobileNumber', title: '手机号' },
      { dataIndex: 'jobNumber', title: '工号' },
      { dataIndex: 'departmentName', title: '组织架构' },
      { dataIndex: 'roleNames', title: '角色' },
      {
        key: 'operate',
        title: '操作',
        fixed: 'right',
        width: 200,
        className: 'text-center!',
        render: (_, row) => (
          <>
            <AekLinkButton onClick={() => edit(row)}>编辑</AekLinkButton>
            <AekLinkButton danger onClick={() => remove(row)}>
              注销
            </AekLinkButton>
            <AekLinkButton danger onClick={() => reset(row)}>
              重置密码
            </AekLinkButton>
            {row.disabled ? (
              <AekLinkButton onClick={() => enable(row)}>启用</AekLinkButton>
            ) : (
              <AekLinkButton danger onClick={() => disable(row)}>
                禁用
              </AekLinkButton>
            )}
          </>
        ),
      },
    ],
    rowSelection: getRowSelection({ type: 'checkbox', selList: selectedRow, setSelList: setSelectedRow }),
  }

  return (
    <PageLayout
      extraSuffix={
        <>
          <AekButton disabled={!selectedRow.length} type='primary' onClick={batchEdit}>
            批量更改
          </AekButton>
          <AekButton type='primary' onClick={add}>
            新建
          </AekButton>
        </>
      }
    >
      <PageLayout.Columns>
        <PageLayout.LeftColumn>
          <Button type='primary' block className='mb10px' onClick={addDept}>
            新增部门
          </Button>
          <AekTree reloadKey={reloadKey} {...treeProps} />
        </PageLayout.LeftColumn>
        <PageLayout.RightColumn>
          <SearchForm {...searchProps} />
          <AekTable {...tableProps} />
        </PageLayout.RightColumn>
      </PageLayout.Columns>
    </PageLayout>
  )
}

export default connect(store => ({
  modelState: store[namespace],
  loading: store.loading,
}))(Index)
